package com.web.config;

import com.web.handler.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy;
import org.springframework.security.web.session.ConcurrentSessionFilter;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;

import java.util.Arrays;

/**
 * @author FDjavaone
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    SecurityMetadataSourceService securityMetadataSourceService;
    @Autowired
    CustomUserService customUserService;
    @Autowired
    MyAccessDecisionManage myAccessDecisionManage;

    @Bean
    public AuthenticationProvider daoAuthenticationProviderImpl() {
        AuthenticationProvider daoAuthenticationProvider = new AuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(new Md5PasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(customUserService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        return daoAuthenticationProvider;
    }

    @Bean
    public MyFilterSecurityInterceptor myFilterSecurityInterceptor() {
        MyFilterSecurityInterceptor myFilterSecurityInterceptor = new MyFilterSecurityInterceptor();
        myFilterSecurityInterceptor.setSecurityMetadataSourceService(securityMetadataSourceService);
        myFilterSecurityInterceptor.setAccessDecisionManager(myAccessDecisionManage);
        return myFilterSecurityInterceptor;
    }

    @Bean
    public MyLogoutSuccessHandler myLogoutSuccessHandler() {
        MyLogoutSuccessHandler myLogoutSuccessHandler = new MyLogoutSuccessHandler();
        return myLogoutSuccessHandler;
    }

    @Bean
    public MyLoginSuccessHandler myLoginSuccessHandler() {
        MyLoginSuccessHandler myLoginSuccessHandler = new MyLoginSuccessHandler();
        myLoginSuccessHandler.setDefaultTargetUrl("/index");
        myLoginSuccessHandler.setAlwaysUseDefaultTargetUrl(true);
        return myLoginSuccessHandler;
    }

    @Bean
    public KdUsernamePasswordAuthenticationFilter kdUsernamePasswordAuthenticationFilter() throws Exception {
        KdUsernamePasswordAuthenticationFilter kdUsernamePasswordAuthenticationFilter = new KdUsernamePasswordAuthenticationFilter();
        kdUsernamePasswordAuthenticationFilter.setAuthenticationManager(this.authenticationManager());
        kdUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(myLoginSuccessHandler());
        kdUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));
        kdUsernamePasswordAuthenticationFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
        return kdUsernamePasswordAuthenticationFilter;
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    /**
     * session失效跳转
     */
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {
        return new SimpleRedirectSessionInformationExpiredStrategy("/login?expired");
    }

    @Bean
    public CompositeSessionAuthenticationStrategy sessionAuthenticationStrategy() {
        ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlAuthenticationStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
        concurrentSessionControlAuthenticationStrategy.setMaximumSessions(3);
        concurrentSessionControlAuthenticationStrategy.setExceptionIfMaximumExceeded(false);
        SessionFixationProtectionStrategy sessionFixationProtectionStrategy = new SessionFixationProtectionStrategy();
        RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistry());
        CompositeSessionAuthenticationStrategy sessionAuthenticationStrategy = new CompositeSessionAuthenticationStrategy(
                Arrays.asList(concurrentSessionControlAuthenticationStrategy, sessionFixationProtectionStrategy, registerSessionStrategy));
        return sessionAuthenticationStrategy;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http.
                addFilterAt(kdUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).addFilterBefore(myFilterSecurityInterceptor(), FilterSecurityInterceptor.class).
                addFilterAt(new ConcurrentSessionFilter(sessionRegistry(), sessionInformationExpiredStrategy()), ConcurrentSessionFilter.class).authorizeRequests()
                .antMatchers("/api/**", "/assets/**", "/swagger/**", "/default/**", "/css/**", "/font/**", "/images/**", "/js/**", "/products/**", "/Widget/**", "*.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout().invalidateHttpSession(true).logoutSuccessHandler(myLogoutSuccessHandler())
                .permitAll();
        http.csrf().ignoringAntMatchers("/api/**", "/default/**");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProviderImpl());
    }

}